﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Sharp.Portal.Mvc.Bootstrap
{
    public static class SelectBoxExtensions
    {
        public static SelectBoxBuilder SelectBox(this BootstrapFactory factory)
        {
            return new SelectBoxBuilder();
        }
        public static SelectBoxBuilder SelectBoxFor<TModel, TProperty>(this BootstrapFactory<TModel> factory,
            Expression<Func<TModel, TProperty>> expression, string valueField)
        {
            return factory.UnobtrusiveValidationAttributes(factory.SelectBox(), expression, valueField);
        }

        public static SelectBoxBuilder WindowUrl(this SelectBoxBuilder builder, string windowUrl)
        {
            builder.WindowUrl = windowUrl;
            return builder;
        }
        public static SelectBoxBuilder ValueField(this SelectBoxBuilder builder, string valueField)
        {
            builder.ValueField = valueField;
            return builder;
        }


        private static SelectBoxBuilder UnobtrusiveValidationAttributes<TModel, TProperty>(this BootstrapFactory<TModel> factory, SelectBoxBuilder builder, Expression<Func<TModel, TProperty>> expression,string valueField)
        {
            var htmlHelper = factory.HtmlHelper;

            var name = ExpressionHelper.GetExpressionText(expression);

            var fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);

            var modelMetadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            


            builder.Id(fullHtmlFieldName).Name(fullHtmlFieldName);

            var text = htmlHelper.FormatValue(modelMetadata.Model, null);
            builder.Text = text;

            var attributes = htmlHelper.GetUnobtrusiveValidationAttributes(name, modelMetadata);
            foreach (var attribute in attributes)
            {
                builder.TextInput.Attribute(attribute.Key, attribute.Value.ToString(), true);
            }


            var modelMetadataValue = ModelMetadata.FromStringExpression(valueField, htmlHelper.ViewData);

            builder.Value = htmlHelper.FormatValue(modelMetadataValue.Model, null);

            return builder;
        }
    }
}
